package com.tzxs.pay.main.mine;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.tzxs.pay.R;
import com.tzxs.pay.databinding.ActivityPasswordChangeBinding;
import com.tzxs.pay.main.base.BaseActivity;
import com.tzxs.pay.main.login.LoginViewModel;
import com.tzxs.pay.util.ISharedPreference;
import com.tzxs.pay.util.StatusBarColorSetter;

import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//支付密码修改
public class PasswordChangeActivity extends BaseActivity<ActivityPasswordChangeBinding> {
    private LoginViewModel model;
    private boolean isShowPassword = false;//默认不显示密码

    @Override
    protected Activity getChildActivity() {
        return this;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_password_change;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarColorSetter.setStatusBarColor(this, Color.parseColor("#FAFAFA"));
        model = ViewModelProviders.of(this).get(LoginViewModel.class);
        //back事件
        dataBinding.passwordChangeToolbar.setNavigationOnClickListener(v -> {
            closeKeyBoard();
            onBackPressed();
        });
        dataBinding.passwordChangeAccount.setText(ISharedPreference.getInstance(getApplication()).getPhone());
        addTextWach(dataBinding.newPassword);
        addTextWach(dataBinding.surePassword);
        //获取短信验证码
        DownTime downTime = new DownTime(60 * 1000 + 500, 1000);
        downTime.bindView(dataBinding.getVerifCode);
        dataBinding.getVerifCode.setOnClickListener(v -> {
            model.getVerCode(dataBinding.passwordChangeAccount.getText().toString(), () -> {
                downTime.start();
            });
        });
        //监听
        model.snackbarEvent.observe(this, s -> {
            if (s != null) {
                Toast.makeText(PasswordChangeActivity.this, s, Toast.LENGTH_SHORT).show();
            }
        });
        //显示 隐藏密码
        dataBinding.visiblePassword.setOnClickListener(v -> {
            if (isShowPassword) {//隐藏密码
                dataBinding.newPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                dataBinding.visiblePassword.setImageResource(R.drawable.ic_invisible_black);
                dataBinding.surePassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                dataBinding.visiblePassword2.setImageResource(R.drawable.ic_invisible_black);
                isShowPassword = false;
            } else {//显示密码
                dataBinding.newPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                dataBinding.visiblePassword.setImageResource(R.drawable.ic_visible_black);
                dataBinding.surePassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                dataBinding.visiblePassword2.setImageResource(R.drawable.ic_visible_black);
                isShowPassword = true;
            }
            dataBinding.newPassword.setSelection(dataBinding.newPassword.getText().length());
        });
        //修改支付密码 提交
        dataBinding.sureChange.setOnClickListener(v -> {
            String newPass = dataBinding.newPassword.getText().toString();
            String surePass = dataBinding.surePassword.getText().toString();
            String account = dataBinding.passwordChangeAccount.getText().toString();
            String code = dataBinding.verifCode.getText().toString();
            //修改密码成功
            model.changePassword(newPass, surePass,
                    account, code, this::finish);
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            closeKeyBoard();
        }
        return super.onKeyDown(keyCode, event);
    }

    //关闭软键盘
    private void closeKeyBoard() {
        InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        View view = getWindow().peekDecorView();
        if (view != null) {
            if (Objects.requireNonNull(manager).isActive()) {
                manager.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
        }
    }

    //约束  输入框
    private void addTextWach(EditText editText) {
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String editable = editText.getText().toString();
                String regEx = "[^a-zA-Z0-9]";  //只能输入字母或数字
                Pattern p = Pattern.compile(regEx);
                Matcher m = p.matcher(editable);
                String str = m.replaceAll("").trim();    //删掉不是字母或数字的字符
                if (!editable.equals(str)) {
                    editText.setText(str);  //设置EditText的字符
                    editText.setSelection(str.length()); //因为删除了字符，要重写设置新的光标所在位置
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    //倒计时
    class DownTime extends CountDownTimer {
        private TextView showView;

        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *                          {@link #onTick(long)} callbacks.
         */
        public DownTime(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onTick(long millisUntilFinished) {
            showView.setEnabled(false);
            showView.setText(millisUntilFinished / 1000 + "s后可重新发送");
        }

        @Override
        public void onFinish() {
            showView.setEnabled(true);
            showView.setText("重新获取验证码");
        }

        //绑定view
        private void bindView(TextView view) {
            this.showView = view;
        }
    }
}
